package com.mapreduce;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.mapreduce.lib.map.RegexMapper;
import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import javax.xml.soap.Text;
import java.net.URI;

public class RegexMapReduce extends Configured implements Tool {
    //
    @Override
    public int run(String[] args) throws Exception {
        Configuration conf = getConf();
        // 设置正则表达式，包含com和Dee开头的
        // .*代表任意个字符，^代表开头
        conf.set("mapreduce.mapper.regex","(.*com.*|^Dee.*)");
        // 指定输入输出路径
        Path input = new Path(
                "hdfs://192.168.10.11:9000/regexdata");
        Path output = new Path(
                "hdfs://192.168.10.11:9000/regexoutput");

        FileSystem fs = FileSystem.get(
                new URI("hdfs://192.168.10.11:9000")
                ,conf);
        if (fs.exists(output)) fs.delete(output,true);

        //构建Job
        Job job = Job.getInstance(conf);
        job.setJobName("regex");
        job.setJarByClass(this.getClass());

        job.setMapperClass(RegexMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(LongWritable.class);

        job.setNumReduceTasks(0);

        TextInputFormat.addInputPath(job,input);
        TextOutputFormat.setOutputPath(job,output);

        return job.waitForCompletion(true)?0:-1;
    }

    public static void main(String[] args) throws Exception {
        System.exit(ToolRunner.run(new RegexMapReduce(),args));
    }
}
